"""
MongoDB 客户端
"""

from pymongo import MongoClient
from pymongo.database import Database

from config import settings


def create_mongo_client(
    uri: str,
    **kwargs,
) -> MongoClient:
    """ 创建 MongoDB 客户端 """

    from components.logger import log

    default_options = {
        "maxPoolSize": 100,  # 最大连接池大小
        "minPoolSize": 10,  # 最小连接池大小
        "maxIdleTimeMS": 60000,  # 连接最大空闲时间
        "retryWrites": True,  # 启用写重试
        "connectTimeoutMS": 5000  # 连接超时时间
    }
    options = {
        **default_options,
        **kwargs,
    }

    try:
        client: MongoClient = MongoClient(uri, **options)
        client.admin.command("ping")  # 测试连接
        log.success("[MongoDB][连接] 成功！")

    except Exception as e:
        log.error(f"[MongoDB][连接] 失败: {str(e)}")
        raise

    return client


mongo_client: MongoClient = create_mongo_client(settings.MONGODB.URI_WITH_REPLICA_SET)
""" MongoDB | 客户端对象 """

mongo_db: Database = mongo_client[settings.MONGODB.DB_NAME]
""" MongoDB | 数据库对象 """
